package msg_list

import (
    "encoding/binary"
    "github.com/pkg/errors"
)

type XNCCMsg interface {
    ProtoID() uint32
    Decode([]byte) error
    Encode()([]byte, error)
}

type MsgWrapper struct {
    ProtoId uint32
    Msg     XNCCMsg
}

type HeartBeat struct {
    timestamp int64
}

func (h *HeartBeat) ProtoID() uint32 {
    return PROTO_HEARTBEAT
}

func (h *HeartBeat) Decode(b []byte) error {
    if len(b) < 8 {
        return errors.New("HeartBeat len is not enough")
    }
    h.timestamp = int64(binary.BigEndian.Uint64(b[0:8]))
    return nil
}

func (h *HeartBeat) Encode()([]byte, error) {
    header := XNCCHeader{
        ProtoId: PROTO_HEARTBEAT,
        BodyLen: 8,
    }
    res := make([]byte, 8)
    header.Encode(res)

    data := make([]byte, 8)
    binary.BigEndian.PutUint64(data[0:8], uint64(h.timestamp))
    res = append(res, data...)
    return res, nil
}

type OnTestMsg struct {
    NumStr string
}

func (h *OnTestMsg) ProtoID() uint32 {
    return PROTO_ON_TEST
}

func (h *OnTestMsg) Decode(b []byte) error {
    if len(b) > 512 {
        return errors.New("OnTestMsg len is error")
    }
    h.NumStr = string(b)
    return nil
}

func (h *OnTestMsg) Encode() ([]byte, error) {
    data := []byte(h.NumStr)
    header := XNCCHeader{
        ProtoId: PROTO_ON_TEST,
        BodyLen: int32(len(data)),
    }
    res := make([]byte, 8)
    header.Encode(res)
    res = append(res, data...)
    return res, nil
}
